package org.corey.share.db.manager;

import javax.persistence.EntityManager;

public abstract class EM {

	private static ThreadLocal<EntityManager> entityManagers = new ThreadLocal<EntityManager>();

	public static EntityManager getEntityManager() {
		EntityManager em = entityManagers.get();
		if (em == null) {
			em = EMF.get().createEntityManager();
		}
		return bindEMToCurrentThread(em);
	}

	public static void clearEntityManager() {
		entityManagers.set(null);
	}

	public static void beginTransaction() {
		EM.getEntityManager().getTransaction().begin();
	}

	public static void commitTransaction() {
		EntityManager em=EM.getEntityManager();
		em.getTransaction().commit();
		em.close();
		clearEntityManager();
	}

	public static void rollback() {
		EM.getEntityManager().getTransaction().rollback();
	}

	private static EntityManager bindEMToCurrentThread(EntityManager em) {
		entityManagers.set(em);
		return em;
	}
}
